﻿using log4net;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interop;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace VirtualWall
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        public static readonly int CLOSE_APP = 0x0801;
        private static readonly ILog log = LogManager.GetLogger("VWApp");

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            // 版本之间逻辑检测和处理
            if (Common.Share.VersionControl.CurrentVersion == Common.Share.VersionType.标准版)
            {
                this.Shutdown();
            }

            //单例运行，一次只能打开一个此程序，再启动的会自动关闭掉
            var processes = Process.GetProcessesByName("ZXVirtualWall");
            if (processes.Length >= 2)
            {
                log.Info("重复开启程序，已经强制关闭新开启的程序！");
                this.Shutdown();
            }
            else
            {
                base.Exit += App_Exit;
             
                //APP程序间传递消息事件
                ComponentDispatcher.ThreadPreprocessMessage += ComponentDispatcher_ThreadPreprocessMessage;

            }
        }

        private void App_Exit(object sender, ExitEventArgs e)
        {
            CloudLogic.CloudAPI.Shutdown();
        }

        private void ComponentDispatcher_ThreadPreprocessMessage(ref MSG msg, ref bool handled)
        {
            if (msg.message == CLOSE_APP)
            {
                try
                {
                    //结束来自称重主程序翻来的关闭程序指令，
                    //在结束程序之前，应当先关闭相关线程、资源的释放操作。

                    //1、关闭云平台服务
                    //CloudLogic.CloudAPI.Shutdown();

                    //最后关闭本程序
                    log.Info("电子围栏程序已经关闭！");
                    Current.Shutdown();
                }
                catch (Exception e)
                {
                    log.Info($"电子围栏关闭出错，具体内容：{e.Message}");
                }
            }
        }
    }
}
